package com.ug_project.spring_dict.DataAccess

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.mchange.v2.c3p0.ComboPooledDataSource
import com.mchange.v2.log.MLevel
import com.mchange.v2.log.MLog
import com.mchange.v2.log.log4j.Log4jMLog
import io.ktor.config.HoconApplicationConfig
import org.jetbrains.exposed.sql.Database
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths

data class DataBaseConnectionConfig(
        var driverClass: String = "",
        var jdbcUrl: String = "",
        var userName: String = "",
        var userPassword: String = "",
        var maxPoolSize: Int = 20,
        var minPoolSize: Int = 5,
        var initialPoolSize: Int = 5
) {
    companion object {
        fun fromFile(fileName: String): DataBaseConnectionConfig {
            if (Files.notExists(Paths.get(fileName))) {
                val retv = DataBaseConnectionConfig()
                val json = GsonBuilder().setPrettyPrinting().create().toJson(retv)
                File(fileName).writeText(json)
            }

            val retv = Gson().fromJson(File(fileName).readText(), DataBaseConnectionConfig::class.java)

            return retv
        }
    }
}

val connectionPool by lazy {
    ComboPooledDataSource().apply {

        val config = DataBaseConnectionConfig.fromFile("DataBaseConfig.json")
        this.driverClass = config.driverClass
        this.jdbcUrl = config.jdbcUrl
        this.user = config.userName
        this.password = config.userPassword
        this.maxPoolSize = config.maxPoolSize
        this.minPoolSize = config.minPoolSize
        this.initialPoolSize = config.initialPoolSize
    }
}

fun connectDb() : Database = Database.connect({ connectionPool.connection})